import { useState, useEffect } from 'react';
import { Select } from 'antd';
import { connect } from 'umi';

import { TRMessage, TRCheckboxModal } from '#/components';
import { HttpCode } from '#/utils/contacts';
import { fetchUsedUnit } from '@/pages/Tianji/RollingBatch/services';

import { SELECT_UNIT_MODEL_TITLE } from '../../constant';
import {
  FETCH_USED_UNIT_DEFAULT_ERROR_MESSAGE,
  NO_UNIT_PERMISSION_WARNING_MESSAGE,
  SELECT_NONE_UNIT_WARNING_MESSAGE,
} from '../../constant/message';
import { clone } from '../../utils';

// 此函数组件主要用于从接口获取数据并处理数据
function SelectStations({
  currentProgramUnitList,
  permissions,
  powerLimitInfo,
  currentProgramInfo,
  currentSequenceId,
  unitTree,
  componentUnitList,
  dispatch,
}) {
  const [options, setOptions] = useState([]);

  useEffect(() => {
    // 处理没有权限的时候下拉框显示名称而不是id
    if (!permissions.modify) {
      setOptions(
        currentProgramUnitList.map((item) => ({
          value: item.unitId,
          label: item.unitTitle,
          disabled: true,
        })),
      );
    } else {
      setOptions(clone(componentUnitList.map((item) => ({ ...item, disabled: true }))));
    }
  }, [currentProgramUnitList]);

  const setUsedUnit = (usedUnitList) => {
    let data = clone(unitTree);
    data.forEach((company) => {
      let isUsedNum = 0;
      (company?.children || []).forEach((station) => {
        // 遍历 usedUnitList，如果当前交易单元在usedUnitList中存在，并且交易单元所属方案与当前方案不同，则禁用当前交易单元
        let isUsed = usedUnitList.find(
          (item) => item.unitId == station.value && item.programTitle != currentProgramInfo?.title,
        );
        if (isUsed) {
          station.disabled = true;
          station.title = station.title + ' (' + isUsed.programTitle + ')';
          isUsedNum++;
        } else {
          let currUnitPowerLimitInfo = powerLimitInfo[station.value];
          if (
            !currUnitPowerLimitInfo ||
            !currUnitPowerLimitInfo[`1`] ||
            (currUnitPowerLimitInfo[`1`]?.buyPowerLimit == null &&
              currUnitPowerLimitInfo[`1`]?.sellPowerLimit == null)
          ) {
            station.disabled = true;
            station.title = station.title + ' (暂无限额信息)';
            isUsedNum++;
          }
        }
      });
      if (isUsedNum === company?.children?.length) {
        company.disabled = true;
      }
    });
    return data;
  };

  const onHandleModal = async () => {
    // 场站权限判断
    if (!unitTree.length) {
      TRMessage.warning(NO_UNIT_PERMISSION_WARNING_MESSAGE);
      return;
    }

    // 获取被占用的交易单元
    dispatch({ type: 'rollingBatch/setAddLoadingNum' });
    const { statusCode, data, message } = await fetchUsedUnit(currentSequenceId);
    dispatch({ type: 'rollingBatch/setSubLoadingNum' });

    if (statusCode === HttpCode.SUCCESS) {
      let treeData = setUsedUnit(data?.usedUnitList || []);
      // 弹窗选择交易单元
      const { checkedNodes } = await TRCheckboxModal.show({
        title: SELECT_UNIT_MODEL_TITLE,
        value: currentProgramUnitList.map((item) => item.unitId),
        treeData,
        okText: '确认',
      });
      if (checkedNodes) {
        if (checkedNodes.length) {
          dispatch({
            type: 'rollingBatch/modifyProgramInfoUnits',
            payload: {
              unitList: checkedNodes.map((item) => ({ unitId: item.key, unitTitle: item.title })),
            },
          });
          TRCheckboxModal.dismiss();
          return;
        }
        TRMessage.error(SELECT_NONE_UNIT_WARNING_MESSAGE);
      }
      return;
    }
    TRMessage.error(message || FETCH_USED_UNIT_DEFAULT_ERROR_MESSAGE);
  };

  return (
    <Select
      value={currentProgramUnitList.map((item) => item.unitId)}
      style={{ width: 190 }}
      options={options}
      placeholder={SELECT_UNIT_MODEL_TITLE}
      mode="multiple"
      maxTagCount={1}
      maxTagTextLength={currentProgramUnitList.length > 1 ? 2 : 8}
      open={false}
      showSearch={false}
      showArrow={true}
      onClick={onHandleModal}
    />
  );
}

export default connect(
  ({
    rollingBatch: {
      currentProgramPermission: permissions,
      powerLimitInfo,
      currentProgramInfo,
      currentUnitList: currentProgramUnitList,
      globalSequence: {
        current: { tradeSequenceId: currentSequenceId },
      },
      unitTree,
      componentUnitList,
    },
  }) => ({
    currentProgramUnitList,
    permissions,
    currentProgramInfo,
    currentSequenceId,
    powerLimitInfo,
    unitTree,
    componentUnitList,
  }),
)(SelectStations);
